package cn.syy.listener;


import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.syy.constants.Constants;
import cn.syy.pojo.domain.Login;
import cn.syy.service.impl.LoginServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 *  程序启动完成后会自动执行类里面的方法
 */
@Component
public class AdminLoginListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private LoginServiceImpl loginService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 获取登录信息里面的admin
        Login login = loginService.getOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getAdmin, true)
                .eq(Login::getType, Constants.Login.TYPE_ADMIN)
                .eq(Login::getUsername, "admin"));
        if (ObjectUtil.isNull(login)){ // 如果获取的信息是空的就创建一个login对象，初始化为admin管理员
            login = new Login();
            login.setUsername("admin");
            String password = "123456";
            String encryptedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
            login.setPassword(encryptedPassword);
            login.setType(Constants.Login.TYPE_ADMIN);
            login.setEnabled(true);
            login.setAvatar(Constants.AVATAR);
            login.setAdmin(true);
            login.setNickName("admin");
            login.setName("admin");
            login.setCreateTime(new Date());
            login.setDeleted(false);
            login.setVersion(0);
            loginService.save(login);
        }
    }

}
